package com.cily.utils.t_webrtc.singlr.Services;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.cily.utils.app.event.Event;
import com.cily.utils.log.L;
import com.cily.utils.t_webrtc.Conf;
import com.cily.utils.t_webrtc.MyApp;
import com.cily.utils.t_webrtc.singlr.Beans.CurrentUser;
import com.cily.utils.t_webrtc.singlr.Beans.MessageBean;
import com.cily.utils.t_webrtc.singlr.Beans.SRUserBean;
import com.cily.utils.t_webrtc.singlr.pad.IndexActivity;
import com.cily.utils.t_webrtc.singlr.phone.AcceptActivity;
import com.cily.utils.t_webrtc.singlr.phone.LoginActivity;
import com.cily.utils.t_webrtc.utils.ObserverUtils;
import com.google.gson.JsonElement;

import microsoft.aspnet.signalr.client.Connection;
import microsoft.aspnet.signalr.client.ErrorCallback;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.StateChangedCallback;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;

public class SignalRService extends Service {
    private Handler mHandler; // to display Toast message
    private final IBinder mBinder = new LocalBinder(); // Binder given to clients
    public static Connection mConnection;
    public static String mConnectionID;

    public SignalRService() {
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(Looper.myLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //flags = START_STICKY;
        int result = super.onStartCommand(intent, flags, startId);

        startSignalR();
        return result;
    }

    @Override
    public void onDestroy() {
        mConnection.stop();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the communication channel to the service.
        startSignalR();
        return mBinder;
    }

    public class LocalBinder extends Binder {
        public SignalRService getService() {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }

    /**
     * method for clients (activities)
     */
    public void sendMessage(String message) {
        mConnection.send(message);
    }

    public  void startSignalR() {
        try {
            //创建 signalR 连接
            mConnection = new Connection(Conf.SIGNALR_HOST){
                @Override
                protected void onConnected() {
                    super.onConnected();
                    L.i("hjz", "startSignalR -> onConnected, Thread: " + Thread.currentThread().getName());
                }

                @Override
                protected void onClosed() {
                    super.onClosed();
                }

                @Override
                public void received(MessageReceivedHandler handler) {
                    super.received(handler);
                }

                @Override
                public void onReceived(JsonElement message) {
                    super.onReceived(message);
                    // To do some logic things
                    String jsonMessage = message.getAsString();
                    MessageBean messageBean = com.alibaba.fastjson.JSONObject.parseObject(jsonMessage, MessageBean.class);
                    L.e(SignalRService.this.getPackageName(), "*****" + messageBean.toString());
                    switch (messageBean.getCode()) {
                        case 0:
                            if (Conf.TYPE.equals(Conf.TYPE_PAD)) {
                                send(ActionMessageService.login("Door", "000000"));
                            }else if (Conf.TYPE.equals(Conf.TYPE_PHONE)){
                                Intent index = new Intent(getBaseContext(), LoginActivity.class);
                                index.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                getBaseContext().startActivity(index);
                            }
                            break;
                        case 1:
                            if (Conf.TYPE.equals(Conf.TYPE_PAD)) {
                                SRUserBean srUserBean = messageBean.getSender();
                                CurrentUser.setCUser(srUserBean);
                                Intent index = new Intent(getBaseContext(), IndexActivity.class);
                                index.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                getBaseContext().startActivity(index);

                                return;
                            }else if (Conf.TYPE.equals(Conf.TYPE_PHONE)){
                                Event e = Event.obtain();
                                e.obj =  messageBean;
                                e.what = Conf.WS_MSG;
                                ObserverUtils.getInstance().send(e);
                                return;
                            }
                            break;

                        case 3:
                        case 6:
                            Intent index = new Intent(getBaseContext(), AcceptActivity.class);
                            index.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            index.putExtra(Conf.INTENT_ICECANDIDATE, messageBean.getData());
                            index.putExtra(Conf.INTENT_CALL_USER, messageBean.getSenderId());
                            getBaseContext().startActivity(index);
                            break;

                    }
                    Event e = Event.obtain();
                    e.obj =  messageBean == null ? jsonMessage : messageBean;
                    e.what = Conf.WS_MSG;
                    ObserverUtils.getInstance().send(e);
                    L.i("hjz", "startSignalR -> onReceived, message: " + message);
                }

                @Override
                public void error(ErrorCallback handler) {
                    super.error(handler);
                }

                @Override
                public void connectionSlow(Runnable handler) {
                    super.connectionSlow(handler);
                }

                @Override
                public void stateChanged(StateChangedCallback handler) {
                    super.stateChanged(handler);
                }
            };
            ClientTransport clientTransport = new ServerSentEventsTransport(mConnection.getLogger());
            mConnectionID = mConnection.getConnectionId();
            mConnection.start(clientTransport);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
